package com.xuqm.sdhbwfu.app.ui

import android.Manifest
import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.view.View.*
import androidx.activity.viewModels
import com.bigkoo.alertview.AlertView
import com.xuqm.base.App
import com.xuqm.base.common.FileHelper
import com.xuqm.base.common.GsonImplHelp
import com.xuqm.base.common.TimeHelper
import com.xuqm.base.common.ToolsHelper
import com.xuqm.base.dialog.loading.LoadingDialog
import com.xuqm.base.extensions.*
import com.xuqm.base.ui.BaseActivity
import com.xuqm.sdhbwfu.app.R
import com.xuqm.sdhbwfu.app.common.SHARE_RISK_LOCATION
import com.xuqm.sdhbwfu.app.common.SHARE_RISK_PURE
import com.xuqm.sdhbwfu.app.data.RiskCreateData
import com.xuqm.sdhbwfu.app.databinding.ActivityRiskCreateBinding
import com.xuqm.sdhbwfu.app.model.RiskLoacationModel
import com.xuqm.sdhbwfu.app.model.RiskPureModel
import com.xuqm.sdhbwfu.app.model.RiskSchemaModel
import com.xuqm.sdhbwfu.app.model.RiskUserModel
import com.xuqm.sdhbwfu.app.viewmodel.RiskCreateViewModel
import java.io.File

class RiskCreateActivity : BaseActivity<ActivityRiskCreateBinding>() {

    override fun getLayoutId(): Int = R.layout.activity_risk_create
    override fun fullscreen(): Boolean = true
    private val listLevel = arrayOf("高", "中", "低")
    private val listType = arrayOf("设备", "位置")

    private val viewModel: RiskCreateViewModel by viewModels()

    private val riskCreateData =
        RiskCreateData(null, null, null, null, null, null, null, null, null, null, "")

    private var address = ""
    private var type = ""

    override fun initData() {
        super.initData()
        viewModel.listLocation.observe(this) {
            LoadingDialog.dismissDialog()
            if (null != it) {
                App.getInstance()
                    .putString(SHARE_RISK_LOCATION, GsonImplHelp.get().toJson(it))
                selectedLocation(it)
            } else {
                showMessage("获取位置数据失败")
            }
        }
        viewModel.listPure.observe(this) {
            LoadingDialog.dismissDialog()
            if (null != it) {
                App.getInstance()
                    .putString(SHARE_RISK_PURE, GsonImplHelp.get().toJson(it))
                selectedPure(it)
            } else {
                showMessage("获取类型数据失败")
            }
        }
        viewModel.listSchema.observe(this) {
            LoadingDialog.dismissDialog()
            if (null != it) {
                selectedSchema(it)
            } else {
                showMessage("没有获取到设备列表")
            }
        }
        viewModel.listUser.observe(this) {
            LoadingDialog.dismissDialog()
            if (null != it) {
                selectedUser(it)
            } else {
                showMessage("没有人员设备列表")
            }
        }
        viewModel.status.observe(this) {
            LoadingDialog.dismissDialog()
            if (null != it) {
                binding.riskAnnexTv.text = "已选择"

                riskCreateData.annex = listOf(RiskCreateData.Annex(it.fsId, it.name))

            } else {
                binding.riskAnnexTv.text = "请选择附件"
                showMessage("上传附件失败")
            }
        }
        viewModel.statusApply.observe(this) {
            LoadingDialog.dismissDialog()
            if (null != it) {
                "提交完成".showMessage()
                finish()

            }
        }
    }

    private fun selectedLocation(it: List<RiskLoacationModel>) {
        if (it.isEmpty()) {
            showMessage("获取位置数据失败")
            return
        }
        val l = it.map { it.name }.toTypedArray()

        AlertView(
            "请选择位置",
            null,
            "",
            l,
            arrayOf("取消"),
            this,
            AlertView.Style.ActionSheet
        ) { _, pos ->
            if (pos < l.size) {
                if (it[pos].children.isNotEmpty()) {
                    App.getInstance().runOnUiThreadDelay({
                        selectedLocation(it[pos].children)
                    }, 300)
                } else {
                    address = it[pos].code
                    binding.riskAddressTv.text = it[pos].name

                    riskCreateData.relationCode = it[pos].code
                    riskCreateData.relationName = it[pos].name

                }
            }
        }.show()
    }

    private fun selectedPure(it: List<RiskPureModel>) {
        if (it.isEmpty()) {
            showMessage("获取类型数据失败")
            return
        }
        val l = it.map { it.name }.toTypedArray()

        AlertView(
            "请选择类型",
            null,
            "",
            l,
            arrayOf("取消"),
            this,
            AlertView.Style.ActionSheet
        ) { _, pos ->
            if (pos < l.size) {
                if (it[pos].children?.isNotEmpty() == true) {
                    App.getInstance().runOnUiThreadDelay({
                        selectedPure(it[pos].children!!)
                    }, 300)
                } else {
                    type = it[pos].code
                    binding.riskPureTv.text = it[pos].name
                }
            }
        }.show()
    }

    private fun selectedSchema(it: List<RiskSchemaModel>) {
        if (it.isEmpty()) {
            showMessage("获取类型数据失败")
            return
        }
        val l = it.map { "$it.name(${it.code})" }.toTypedArray()

        AlertView(
            "请选择位置",
            null,
            "",
            l,
            arrayOf("取消"),
            this,
            AlertView.Style.ActionSheet
        ) { _, pos ->
            if (pos < l.size) {
                binding.riskSchemaTv.text = l[pos]
                riskCreateData.relationCode = it[pos].code
                riskCreateData.relationName = it[pos].name
            }
        }.show()
    }

    private fun selectedUser(it: List<RiskUserModel>) {
        if (it.isEmpty()) {
            showMessage("获取人员列表失败")
            return
        }
        val l = it.map { it.name }.toTypedArray()

        AlertView(
            "请选择审批人",
            null,
            "",
            l,
            arrayOf("取消"),
            this,
            AlertView.Style.ActionSheet
        ) { _, pos ->
            if (pos < l.size) {
                binding.riskApprovalTv.text = l[pos]
                riskCreateData.approvalCode = it[pos].id.toString()
                riskCreateData.approvalName = it[pos].name
            }
        }.show()
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        binding.inspectionBackLyt.setOnClickListener { finish() }

        binding.createLevel.setOnClickListener {
            AlertView(
                "请选择风险等级",
                null,
                "",
                listLevel,
                arrayOf("取消"),
                this,
                AlertView.Style.ActionSheet
            ) { _, pos ->
                if (pos != 3) {
                    riskCreateData.eventLevel = "${pos + 1}";
                    binding.createLevelMsg.text = listLevel[pos]
                }
            }.show()
        }
        binding.riskType.setOnClickListener {
            AlertView(
                "请选择风险关联类型",
                null,
                "",
                listType,
                arrayOf("取消"),
                this,
                AlertView.Style.ActionSheet
            ) { _, pos ->
                if (pos != 2) {
                    riskCreateData.riskType = "${pos + 1}";
                    binding.riskTypeTv.text = listType[pos]
                    if (pos == 0) {
                        binding.riskT.visibility = VISIBLE
                        binding.riskApp.visibility = VISIBLE
                    } else if (pos == 1) {
                        binding.riskT.visibility = INVISIBLE
                        binding.riskApp.visibility = GONE
                    }
                }
            }.show()
        }
        binding.riskAddressLyt.setOnClickListener {

            val msg = App.getInstance().getStringForPreferences(SHARE_RISK_LOCATION, "")

            if (msg.isEmpty() || "[]" == msg) {
                LoadingDialog.showDialog("")
                viewModel.locationList()
            } else {
                selectedLocation(GsonImplHelp.get().toList(msg, RiskLoacationModel::class.java))

            }

        }
        binding.riskPureLyt.setOnClickListener {

            val msg = App.getInstance().getStringForPreferences(SHARE_RISK_PURE, "")

            if (msg.isEmpty() || "[]" == msg) {
                LoadingDialog.showDialog("")
                viewModel.pureList()
            } else {
                selectedPure(GsonImplHelp.get().toList(msg, RiskPureModel::class.java))
            }

        }
        binding.riskSchemaLyt.setOnClickListener {
            if (address.isEmpty() || type.isEmpty()) {
                "请先选择位置和类型".showMessage()
                return@setOnClickListener
            }
            LoadingDialog.showDialog("")
            viewModel.schemaList(type, address)
        }
        binding.riskApprovalLyt.setOnClickListener {
            LoadingDialog.showDialog("")
            viewModel.userList()
        }
        binding.riskAnnex.setOnClickListener {

            runWithPermission(
                Manifest.permission.CAMERA,
                rationaleMethod = {
                    AlertView(
                        "无法获取摄像头使用权限", "上传附件需要开启相机权限才能使用。",
                        null, arrayOf("确定"), null, mContext,
                        AlertView.Style.Alert
                    ) { _, _ ->
                    }.show()
                },
                permanentDeniedMethod = {
                    "请在设置界面打开摄像头权限".showMessage()
                    AlertView(
                        "无法获取摄像头使用权限", "上传附件需要开启相机权限才能使用，请在应用权限管理页面打开相关权限。",
                        null, arrayOf("确定"), null, mContext,
                        AlertView.Style.Alert
                    ) { _, _ ->
                    }.show()
                },
                callback = {
                    dispatchTakePictureIntent()
                })
        }
        binding.riskConfirm.setOnClickListener {

            if (ToolsHelper.isNull(binding.riskTitle.text.toString())) {
                "请输入标题内容".showMessage()
                return@setOnClickListener
            }
            riskCreateData.title = binding.riskTitle.text.toString()
            if (ToolsHelper.isNull(binding.riskDescription.text.toString())) {
                "请输入风险描述".showMessage()
                return@setOnClickListener
            }
            riskCreateData.riskDescription = binding.riskDescription.text.toString()
            if ("风险等级" == binding.createLevelMsg.text.toString()) {
                "请选择风险等级".showMessage()
                return@setOnClickListener
            }
            if ("选择人员" == binding.riskApprovalTv.text.toString()) {
                "请审批人员".showMessage()
                return@setOnClickListener
            }
            riskCreateData.toString().loge()
            viewModel.applyForm(riskCreateData)
        }
    }

    lateinit var photoPath: String
    val REQUEST_IMAGE_CAPTURE = 10013

    private fun dispatchTakePictureIntent() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // Ensure that there's a camera activity to handle the intent
            val c: ComponentName? = takePictureIntent.resolveActivity(packageManager)
            if (null == c) {
                "启动相机失败".showMessage()
            } else {
                val photoURI = FileHelper.getFileUri(
                    File.createTempFile(
                        TimeHelper.getTimeMillis().toString(),
                        ".jpg",
                        File(FileHelper.getImagePath())
                    ).also { photoPath = it.absolutePath }
                )

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            if (resultCode == RESULT_OK) {
                LoadingDialog.showDialog("")
                viewModel.picUpload(File(photoPath))
            }

        }
    }
}